﻿using Edu.Abstracts;
using Edu.Contracts;
using Edu.Utilities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace Edu.Services
{
    public class FileAppService : ApplicationService, IFileAppService
    {
        private readonly IHostingEnvironment env;
        public const string StoreDir = "Store";

        public FileAppService(IHostingEnvironment hostingEnvironment)
        {
            this.env = hostingEnvironment;
        }

        public virtual async Task<FileInfoDto> Upload(IFormFile file, string dir)
        {
            var fileName = file.GetFilename();
            var fileExtension = Path.GetExtension(fileName);

            var subdir = DateTimeOffset.UtcNow.ToString("yyyyMMdd");

            var fileDir = Path.Combine(this.env.WebRootPath, StoreDir, dir, subdir);
            if (!Directory.Exists(fileDir))
                Directory.CreateDirectory(fileDir);

            var path = Path.Combine(fileDir, FileHelpers.GetUniqueFileName(fileName));

            using (FileStream stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            var entity = new FileInfoDto
            {
                FilePath = path,
                WebPath = path.Replace(this.env.WebRootPath, "").Replace('\\', '/'),
                FileExtension = fileExtension,
                ContentType = file.ContentType,
                ContentLength = file.Length
            };
            return entity;
        }
    }
}
